<template>
  <div class="threat-intel">
    <el-card class="list-card">
      <template #header>
        <div class="header">
          <h2>威胁情报浏览</h2>
          <el-input
            v-model="searchQuery"
            placeholder="搜索威胁情报..."
            prefix-icon="el-icon-search"
            clearable
            @input="handleSearch"
            class="search-input"
          />
        </div>
      </template>
      <div class="content">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="10" animated />
        </div>
        
        <div v-else-if="intelList.length === 0" class="empty-container">
          <el-empty description="暂无威胁情报数据">
            <el-button type="primary" @click="navigateToExtract">
              提取情报
            </el-button>
          </el-empty>
        </div>
        
        <div v-else class="intel-list">
          <el-table
            :data="filteredIntelList"
            style="width: 100%"
            @row-click="handleRowClick"
            :default-sort="{ prop: 'timestamp', order: 'descending' }"
          >
            <el-table-column prop="title" label="标题" min-width="250">
              <template #default="scope">
                <div class="intel-title">{{ scope.row.title }}</div>
                <div class="intel-source">来源: {{ scope.row.source }}</div>
              </template>
            </el-table-column>
            
            <el-table-column prop="entity_count" label="实体数量" width="100" sortable>
              <template #default="scope">
                <el-tag size="small">{{ scope.row.entity_count }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="relation_count" label="关系数量" width="100" sortable>
              <template #default="scope">
                <el-tag size="small" type="success">{{ scope.row.relation_count }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="timestamp" label="时间" width="180" sortable>
              <template #default="scope">
                {{ formatDate(scope.row.timestamp) }}
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  @click.stop="viewIntelDetails(scope.row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-if="intelList.length > pageSize"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="intelList.length"
              layout="total, prev, pager, next"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="selectedIntel ? selectedIntel.title : '威胁情报详情'"
      size="60%"
      direction="rtl"
    >
      <div v-if="selectedIntel" class="intel-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="标题">
            {{ selectedIntel.title }}
          </el-descriptions-item>
          <el-descriptions-item label="来源">
            <el-link :href="selectedIntel.link" target="_blank" type="primary" v-if="selectedIntel.link">
              {{ selectedIntel.source }}
            </el-link>
            <span v-else>{{ selectedIntel.source }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="时间">
            {{ formatDate(selectedIntel.timestamp) }}
          </el-descriptions-item>
          <el-descriptions-item label="实体数量">
            {{ selectedIntel.entity_count }}
          </el-descriptions-item>
          <el-descriptions-item label="关系数量">
            {{ selectedIntel.relation_count }}
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider>原始内容</el-divider>
        
        <div class="intel-content">{{ selectedIntel.content }}</div>
        
        <el-divider>提取实体</el-divider>
        
        <el-collapse>
          <el-collapse-item v-for="(items, type) in groupedEntities" :key="type" :title="`${type} (${items.length})`">
            <div class="entity-items">
              <el-tag
                v-for="(entity, index) in items"
                :key="index"
                class="entity-tag"
                :type="getEntityTagType(type)"
                effect="plain"
              >
                {{ entity.name }}
              </el-tag>
            </div>
          </el-collapse-item>
        </el-collapse>
        
        <div class="action-buttons">
          <el-button type="success" @click="navigateToGraph">
            在图谱中查看
          </el-button>
          <el-button type="primary" @click="navigateToTrust">
            评估可信度
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loading = ref(true)
const searchQuery = ref('')
const intelList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const drawerVisible = ref(false)
const selectedIntel = ref(null)
const groupedEntities = ref({})

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '未知时间'
  
  const date = new Date(timestamp)
  return date.toLocaleString()
}

// 获取威胁情报数据
const fetchIntelData = async () => {
  loading.value = true
  
  try {
    // Mock data instead of fetching from server
    setTimeout(() => {
      const fixedContent = "U.S. intelligence agencies recently identified a Russian cybersecurity firm, wh as having close ties to Moscow\u2019s Federal Security Service, the civilian intelligence cyberintelligence officials that Moscow is stepping up covert efforts to infiltrate compute taking steps to open a U.S. branch office as part of the intelligence-gathering, said officiidentify it by name. However, security officials are quietly alerting government security c Russian firm is said to have extensive technical experience in security vulnerabilities of s employed by both government and private-sector system controllers for equipment run farms and large communication systems."
      
      intelList.value = [
        {
          id: "1",
          title: "Russian Cybersecurity Firm Ties to FSB",
          content: fixedContent,
          source: "Intelligence Report",
          timestamp: new Date().toISOString(),
          entity_count: 5,
          relation_count: 3
        }
      ]
      
      loading.value = false
    }, 1000)
  } catch (error) {
    console.error('获取威胁情报失败:', error)
    ElMessage.error('获取威胁情报失败')
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
}

// 计算当前页的数据
const filteredIntelList = computed(() => {
  const query = searchQuery.value.toLowerCase()
  
  const filtered = intelList.value.filter(intel => 
    intel.title.toLowerCase().includes(query) || 
    intel.content.toLowerCase().includes(query) ||
    intel.source.toLowerCase().includes(query)
  )
  
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  
  return filtered.slice(start, end)
})

// 行点击处理
const handleRowClick = (row) => {
  viewIntelDetails(row)
}

// 查看情报详情
const viewIntelDetails = async (intel) => {
  try {
    // Use mock data instead of fetching from server
    selectedIntel.value = {
      ...intel,
      id: intel.id,
      title: intel.title,
      content: intel.content,
      source: intel.source,
      timestamp: intel.timestamp,
      entity_count: intel.entity_count,
      relation_count: intel.relation_count
    }
    
    // Mock entities data
    const entities = [
      { id: "e1", name: "Russian cybersecurity firm", type: "Organization" },
      { id: "e2", name: "Moscow Federal Security Service", type: "Organization" },
      { id: "e3", name: "United States", type: "System" },
      { id: "e4", name: "Security vulnerabilities", type: "Malware" },
      { id: "e5", name: "Intelligence gathering", type: "Entity" }
    ]
    
    // Group entities by type
    const grouped = {}
    entities.forEach(entity => {
      if (!grouped[entity.type]) {
        grouped[entity.type] = []
      }
      grouped[entity.type].push(entity)
    })
    
    groupedEntities.value = grouped
    drawerVisible.value = true
  } catch (error) {
    console.error('获取情报详情失败:', error)
    ElMessage.error('获取情报详情失败')
  }
}

// 获取实体标签类型
const getEntityTagType = (entityType) => {
  const typeMap = {
    'ThreatActor': 'danger',
    'Malware': 'warning',
    'Tool': 'info',
    'Vulnerability': 'warning',
    'AttackPattern': 'danger',
    'Identity': 'success',
    'Indicator': 'info',
    'Infrastructure': 'primary'
  }
  
  return typeMap[entityType] || ''
}

// 导航到提取页面
const navigateToExtract = () => {
  router.push('/dashboard/extract')
}

// 导航到图谱页面
const navigateToGraph = () => {
  router.push('/dashboard/graph')
}

// 导航到可信度评估页面
const navigateToTrust = () => {
  router.push('/dashboard/trust')
}

onMounted(() => {
  fetchIntelData()
})
</script>

<style scoped>
.threat-intel {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h2 {
  margin: 0;
  font-size: 18px;
}

.search-input {
  width: 300px;
}

.content {
  min-height: 400px;
}

.loading-container, .empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.intel-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.intel-source {
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.intel-details {
  padding: 20px;
}

.intel-content {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  white-space: pre-line;
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.entity-items {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.entity-tag {
  margin-bottom: 8px;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style> 